// pages/shopManager/shopService/serviceEdit/serviceEdit.js
const common = require('../../../../utils/util.js')
const md5 = require('../../../../utils/md5.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        demoId: null,
        goodsId: null,
        goodsInfo: null,
        goodsMainImg: '',
        goodsName: '',
        goodsBrief: '',
        classifyList: [],
        goodsClassifyList: [],
        goodsClassifyIndex: null,
        addClassifyShow: false,
        addClassifyName: '',
        goodsFormat: [{
            color: '',
            img: '',
            price: '',
            retail_price: '',
            sku_num: ''
        }],
        goodsNeedKnow: [],
        goodsSubImg: [],
        goodsDetailImg: [],
        onSale: true,
        isActivity: false,
        goodsActivityImg: '',
        isLoading: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (options.goodsId) {
            this.setData({
                goodsId: options.goodsId
            })
        }
        if (options.demoId) {
            this.setData({
                demoId: options.demoId
            })
        }
        this.getGoodsClassify()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        let pages = getCurrentPages(); //获取当前页面实例
        let prepage = pages[pages.length - 2]
        if (prepage == undefined || prepage == null) return;
        prepage.updateData()
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    getGoodsClassify: function() {
        const that = this
        let data = {
            store_id: wx.getStorageSync('storeId'),
            show_type: 2,
            page: 0,
            limit: 999
        }
        common.post('Goodsclass/store_class_list', data).then(function(res) {
            if (res.code == 204) {
                return
            }
            let goodsClassifyList = []
            res.forEach((e) => {
                goodsClassifyList.push(e.class_name)
            }).end(
                function() {
                    that.setData({
                        classifyList: res,
                        goodsClassifyList: goodsClassifyList
                    })
                    if (that.data.goodsId) {
                        that.getGoodsInfo()
                    }
                    if (that.data.demoId) {
                        that.getDemoInfo()
                    }
                }
            )

        }).catch(function(e) {})
    },

    getDemoInfo: function() {
        wx.showLoading({
            title: '加载中'
        })
        const that = this
        let data = {
            goods_id: this.data.demoId,
            is_goods: 9,
            paramter: 1
        }
        common.post('Goods/goods_list', data).then(function(res) {
            wx.hideLoading()
            if (res.code == 204) {
                return
            }
            that.setData({
                goodsMainImg: {
                    major_img_big: res[0].image,
                    major_img_middle: res[0].image_middle,
                    major_img_thumb: res[0].image_thumb
                },
                goodsName: res[0].goods_name,
                goodsBrief: res[0].brief,
                goodsFormat: res[0].sku,
                goodsNeedKnow: res[0].parameter,
                goodsSubImg: res[0].vice_big,
                goodsDetailImg: res[0].info
            })
        }).catch(function(e) {})
    },

    getGoodsInfo: function() {
        wx.showLoading({
            title: '加载中'
        })
        const that = this
        let data = {
            goods_id: this.data.goodsId,
            client: 1,
            paramter: 1
        }
        common.post('Goods/goods_list', data).then(function(res) {
            wx.hideLoading()
            if (res.code == 204) {
                return
            }
            that.setData({
                goodsMainImg: {
                    major_img_big: res[0].image,
                    major_img_middle: res[0].image_middle,
                    major_img_thumb: res[0].image_thumb
                },
                goodsClassifyIndex: String(that.data.classifyList.findIndex((e) => {
                    return e.class_id == res[0].class_id
                })) == -1 ? '0' : String(that.data.classifyList.findIndex((e) => {
                    return e.class_id == res[0].class_id
                })),
                goodsName: res[0].goods_name,
                goodsBrief: res[0].brief,
                goodsFormat: res[0].sku,
                goodsNeedKnow: res[0].parameter,
                goodsSubImg: res[0].vice_big,
                goodsDetailImg: res[0].info,
                goodsActivityImg: res[0].actvity_img,
                onSale: res[0].is_sale == 1 ? true : false,
                isActivity: res[0].is_actvity == 1 ? true : false,
            })
        }).catch(function(e) {})
    },

    goodsNameInput: function(e) {
        this.setData({
            goodsName: e.detail.value
        })
    },

    goodsBriefInput: function(e) {
        this.setData({
            goodsBrief: e.detail.value
        })
    },

    goodsClassifyChange: function(e) {
        this.setData({
            goodsClassifyIndex: e.detail.value
        })
    },

    goAddClassify: function() {
        this.setData({
            addClassifyShow: true
        })
    },

    myCatchTouch: function() {
        return
    },

    cancleClassifyShow: function() {
        this.setData({
            addClassifyShow: false
        })
    },

    classifyNameInput: function(e) {
        this.setData({
            addClassifyName: e.detail.value
        })
    },

    sureAddClassify: function() {
        wx.showLoading({
            title: '请稍后'
        })
        const that = this
        let data = {
            store_id: wx.getStorageSync('storeId'),
            class_name: this.data.addClassifyName
        }
        common.post('Goodsclass/store_add_class', data).then(function(res) {
            wx.hideLoading()
            if (res.code == 204) {
                wx.showModal({
                    title: '提示',
                    content: res.error,
                    showCancel: false,
                    success(res) {}
                })
                that.setData({
                    addClassifyShow: false,
                    addClassifyName: ''
                })
                return
            }
            wx.showModal({
                title: '提示',
                content: '成功新建分类',
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            addClassifyShow: false,
                            addClassifyName: ''
                        })
                        let data = {
                            store_id: wx.getStorageSync('storeId'),
                            page: 0,
                            limit: 999
                        }
                        common.post('Goodsclass/store_class_list', data).then(function(res) {
                            if (res.code == 204) {
                                return
                            }
                            let goodsClassifyList = []
                            res.forEach((e) => {
                                goodsClassifyList.push(e.class_name)
                            }).end(
                                function() {
                                    that.setData({
                                        classifyList: res,
                                        goodsClassifyList: goodsClassifyList,
                                        goodsClassifyIndex: that.data.goodsClassifyIndex * 1 + 1
                                    })
                                }
                            )

                        }).catch(function(e) {})
                    }
                }
            })
        }).catch(function(e) {})
    },

    formatNameInput: function(e) {
        let goodsFormat = this.data.goodsFormat
        goodsFormat[e.currentTarget.dataset.index].color = e.detail.value
        this.setData({
            goodsFormat: goodsFormat
        })
    },

    formatFactoryPriceInput: function(e) {
        let goodsFormat = this.data.goodsFormat
        goodsFormat[e.currentTarget.dataset.index].factory_price = e.detail.value
        this.setData({
            goodsFormat: goodsFormat
        })
    },

    marketPriceInput: function(e) {
        let goodsFormat = this.data.goodsFormat
        goodsFormat[e.currentTarget.dataset.index].price = e.detail.value
        this.setData({
            goodsFormat: goodsFormat
        })
    },

    formatPriceInput: function(e) {
        let goodsFormat = this.data.goodsFormat
        goodsFormat[e.currentTarget.dataset.index].retail_price = e.detail.value
        this.setData({
            goodsFormat: goodsFormat
        })
    },

    formatStockInput: function(e) {
        let goodsFormat = this.data.goodsFormat
        goodsFormat[e.currentTarget.dataset.index].sku_num = e.detail.value
        this.setData({
            goodsFormat: goodsFormat
        })
    },

    goodsBonusInput: function(e) {
        let goodsFormat = this.data.goodsFormat
        goodsFormat[e.currentTarget.dataset.index].royalty = e.detail.value
        this.setData({
            goodsFormat: goodsFormat
        })
    },

    addFormat: function() {
        let goodsFormat = this.data.goodsFormat
        let formatData = {
            color: '',
            img: '',
            price: '',
            factory_price: '',
            sku_num: ''
        }
        goodsFormat.push(formatData)
        this.setData({
            goodsFormat: goodsFormat
        })
    },

    deleteFormat: function(e) {
        const that = this
        let goodsFormat = this.data.goodsFormat
        if (this.data.goodsId == null) {
            goodsFormat.splice(e.currentTarget.dataset.index, 1)
            this.setData({
                goodsFormat: goodsFormat
            })
        } else {
            wx.showLoading({
                title: '请稍后'
            })
            let data = {
                sku_id: e.currentTarget.dataset.id
            }
            common.post('Goods/del_sku', data).then(function(res) {
                wx.hideLoading()
                if (res.code == 204) {
                    wx.showModal({
                        title: '提示',
                        content: res.error,
                        showCancel: false,
                        success(res) {}
                    })
                    return
                }
                wx.showModal({
                    title: '提示',
                    content: '删除规格成功',
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            goodsFormat.splice(e.currentTarget.dataset.index, 1)
                            that.setData({
                                goodsFormat: goodsFormat
                            })
                        }
                    }
                })
            })
        }
    },

    addNeedKonw: function() {
        let goodsNeedKnow = this.data.goodsNeedKnow
        goodsNeedKnow.push({
            parameter_key: '',
            parameter_value: ''
        })
        this.setData({
            goodsNeedKnow: goodsNeedKnow
        })
    },

    deleteNeedKnow: function(e) {
        const that = this
        let goodsNeedKnow = this.data.goodsNeedKnow
        if (this.data.goodsId == null) {
            goodsNeedKnow.splice(e.currentTarget.dataset.index, 1)
            this.setData({
                goodsNeedKnow: goodsNeedKnow
            })
        } else {
            wx.showLoading({
                title: '请稍后'
            })
            let data = {
                parameter_id: e.currentTarget.dataset.id
            }
            common.post('Goods/del_parameter', data).then(function(res) {
                wx.hideLoading()
                if (res.code == 204) {
                    wx.showModal({
                        title: '提示',
                        content: res.error,
                        showCancel: false,
                        success(res) {}
                    })
                    return
                }
                wx.showModal({
                    title: '提示',
                    content: '删除购买须知成功',
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            goodsNeedKnow.splice(e.currentTarget.dataset.index, 1)
                            that.setData({
                                goodsNeedKnow: goodsNeedKnow
                            })
                        }
                    }
                })
            })
        }
    },

    needKonwNameInput: function(e) {
        let goodsNeedKnow = this.data.goodsNeedKnow
        goodsNeedKnow[e.currentTarget.dataset.index].parameter_key = e.detail.value
        this.setData({
            goodsNeedKnow: goodsNeedKnow
        })
    },

    needKnowInfoInput: function(e) {
        let goodsNeedKnow = this.data.goodsNeedKnow
        goodsNeedKnow[e.currentTarget.dataset.index].parameter_value = e.detail.value
        this.setData({
            goodsNeedKnow: goodsNeedKnow
        })
    },

    deleteSubImg: function(e) {
        const that = this
        let goodsSubImg = this.data.goodsSubImg
        if (this.data.goodsId == null) {
            goodsSubImg.splice(e.currentTarget.dataset.index, 1)
            this.setData({
                goodsSubImg: goodsSubImg
            })
        } else {
            wx.showLoading({
                title: '请稍后'
            })
            let data = {
                image_id: e.currentTarget.dataset.id
            }
            common.post('Goods/del_goods_img', data).then(function(res) {
                wx.hideLoading()
                if (res.code == 204) {
                    wx.showModal({
                        title: '提示',
                        content: res.error,
                        showCancel: false,
                        success(res) {}
                    })
                    return
                }
                wx.showModal({
                    title: '提示',
                    content: '删除图片成功',
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            goodsSubImg.splice(e.currentTarget.dataset.index, 1)
                            that.setData({
                                goodsSubImg: goodsSubImg
                            })
                        }
                    }
                })
            })
        }
    },

    deleteDetailImg: function(e) {
        const that = this
        let goodsDetailImg = this.data.goodsDetailImg
        if (this.data.goodsId == null) {
            goodsDetailImg.splice(e.currentTarget.dataset.index, 1)
            this.setData({
                goodsDetailImg: goodsDetailImg
            })
        } else {
            wx.showLoading({
                title: '请稍后'
            })
            let data = {
                image_id: e.currentTarget.dataset.id
            }
            common.post('Goods/del_goods_img', data).then(function(res) {
                wx.hideLoading()
                if (res.code == 204) {
                    wx.showModal({
                        title: '提示',
                        content: res.error,
                        showCancel: false,
                        success(res) {}
                    })
                    return
                }
                wx.showModal({
                    title: '提示',
                    content: '删除图片成功',
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            goodsDetailImg.splice(e.currentTarget.dataset.index, 1)
                            that.setData({
                                goodsDetailImg: goodsDetailImg
                            })
                        }
                    }
                })
            })
        }
    },

    shopIntroChange: function(e) {
        this.setData({
            shopIntro: e.detail.value
        })
    },

    onSaleChange: function(e) {
        this.setData({
            onSale: e.detail.value
        })
    },

    isActivityChange: function(e) {
        this.setData({
            isActivity: e.detail.value
        })
    },

    goSave: function() {
        if (this.data.isLoading) {
            return
        }
        if (this.data.goodsMainImg == '') {
            wx.showToast({
                title: '请添加项目主图',
                icon: 'none',
                duration: 2000
            })
            return
        }
        if (this.data.goodsName == '') {
            wx.showToast({
                title: '请填写项目标题',
                icon: 'none',
                duration: 2000
            })
            return
        }
        if (this.data.goodsClassifyIndex == null || this.data.goodsClassifyIndex == -1) {
            wx.showToast({
                title: '请选择项目分类',
                icon: 'none',
                duration: 2000
            })
            return
        }
        if (this.data.goodsFormat.find((e) => {
                if (e.color == '' || e.img == '' || e.price == '' || e.retail_price == '' || e.sku_num == '') {
                    return true
                }
            })) {
            wx.showToast({
                title: '请完善项目规格信息',
                icon: 'none',
                duration: 2000
            })
            return
        }
        if (this.data.goodsNeedKnow.find((e) => {
                if (e.parameter_key == '' || e.parameter_value == '') {
                    return true
                }
            })) {
            wx.showToast({
                title: '请完善项目购买须知信息',
                icon: 'none',
                duration: 2000
            })
            return
        }
        if (this.data.goodsSubImg.length == 0) {
            wx.showToast({
                title: '请添加项目副图',
                icon: 'none',
                duration: 2000
            })
            return
        }
        if (this.data.goodsDetailImg.length == 0) {
            wx.showToast({
                title: '请添加项目详情图',
                icon: 'none',
                duration: 2000
            })
            return
        }
        if (this.data.isActivity && this.data.goodsActivityImg == '') {
            wx.showToast({
                title: '请添加项目活动轮播图',
                icon: 'none',
                duration: 2000
            })
            return
        }
        this.setData({
            isLoading: true
        })
        wx.showLoading({
            title: '保存中',
        })
        const that = this
        let data
        if (this.data.goodsId == null) {
            data = {
                client: 1,
                goods_name: this.data.goodsName,
                store_id: wx.getStorageSync('storeId'),
                brief: this.data.goodsBrief,
                class_id: this.data.classifyList[this.data.goodsClassifyIndex].class_id,
                image: this.data.goodsMainImg.major_img_big,
                image_middle: this.data.goodsMainImg.major_img_middle,
                image_thumb: this.data.goodsMainImg.major_img_thumb,
                viceImages: JSON.stringify(this.data.goodsSubImg),
                infoImages: JSON.stringify(this.data.goodsDetailImg),
                sku_list: JSON.stringify(this.data.goodsFormat),
                parameter_list: JSON.stringify(this.data.goodsNeedKnow),
                is_sale: this.data.onSale ? '1' : '0',
                is_actvity: this.data.isActivity ? '1' : '0',
                actvity_img: this.data.goodsActivityImg
            }
            common.post('Goods/add_goods', data).then(function(res) {
                wx.hideLoading()
                that.setData({
                    isLoading: false
                })
                if (res.code == 204) {
                    wx.showModal({
                        title: '提示',
                        content: res.error,
                        showCancel: false,
                        success(res) {}
                    })
                    return
                }
                wx.showModal({
                    title: '提示',
                    content: '新增项目成功',
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            wx.navigateBack({
                                delta: 1
                            })
                        }
                    }
                })
            }).catch(function(e) {})
        } else {
            data = {
                client: 1,
                goods_id: this.data.goodsId,
                goods_name: this.data.goodsName,
                store_id: wx.getStorageSync('storeId'),
                brief: this.data.goodsBrief,
                class_id: this.data.classifyList[this.data.goodsClassifyIndex].class_id,
                image: this.data.goodsMainImg.major_img_big,
                image_middle: this.data.goodsMainImg.major_img_middle,
                image_thumb: this.data.goodsMainImg.major_img_thumb,
                sku_list: JSON.stringify(this.data.goodsFormat),
                parameter_list: JSON.stringify(this.data.goodsNeedKnow),
                is_sale: this.data.onSale ? '1' : '0',
                is_actvity: this.data.isActivity ? '1' : '0',
                actvity_img: this.data.goodsActivityImg
            }
            common.post('Goods/up_goods', data).then(function(res) {
                wx.hideLoading()
                that.setData({
                    isLoading: false
                })
                if (res.code == 204) {
                    wx.showModal({
                        title: '提示',
                        content: res.error,
                        showCancel: false,
                        success(res) {}
                    })
                    return
                }
                wx.showModal({
                    title: '提示',
                    content: '保存项目成功',
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            wx.navigateBack({
                                delta: 1
                            })
                        }
                    }
                })
            }).catch(function(e) {})
        }
    },

    uploadImg: function(e) {
        const that = this
        let data = {}
        let key = wx.getStorageSync('token')
        let sign = 'cds'
        let timestamp = Date.parse(new Date())
        data.key = key
        data.timestamp = timestamp
        data = this.objKeySort(data)
        for (let i in data) {
            sign += (i + data[i])
        }
        sign += 'cds'
        sign = md5(sign)
        data.sign = sign
        wx.chooseImage({
            count: e.currentTarget.dataset.type == 'mainImg' || e.currentTarget.dataset.type == 'formatImg' || e.currentTarget.dataset.type == 'activityImg' ? 1 : 9, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function(res) {
                wx.showLoading({
                    title: '正在上传图片',
                })
                let tempFilePaths = res.tempFilePaths
                if (e.currentTarget.dataset.type == 'mainImg') {
                    wx.navigateTo({
                        url: '/pages/cropper/cropper?type=2&target=goodsMainImg&src=' + tempFilePaths + '&ratio=true&width=240&height=240'
                    })
                } else if (e.currentTarget.dataset.type == 'formatImg') {
                    wx.uploadFile({
                        url: 'https://www.meiboshi.vip/api/Upimg/up_sku_img', //仅为示例，非真实的接口地址
                        filePath: tempFilePaths[0],
                        name: 'file',
                        formData: {
                            key: data.key,
                            timestamp: data.timestamp,
                            sign: data.sign
                        },
                        success(res) {
                            wx.hideLoading()
                            if (JSON.parse(res.data).code == 204) {
                                wx.showModal({
                                    title: '提示',
                                    content: JSON.parse(res.data).error,
                                    showCancel: false
                                })
                                return
                            }
                            wx.showToast({
                                title: '上传图片成功',
                                icon: 'none',
                                duration: 2000
                            })
                            let goodsFormat = that.data.goodsFormat
                            goodsFormat[e.currentTarget.dataset.index].img = JSON.parse(res.data).datas
                            that.setData({
                                goodsFormat: goodsFormat
                            })
                        }
                    })
                } else if (e.currentTarget.dataset.type == 'activityImg') {
                    wx.uploadFile({
                        url: 'https://www.meiboshi.vip/api/Upimg/up_comment_img', //仅为示例，非真实的接口地址
                        filePath: tempFilePaths[0],
                        name: 'file',
                        formData: {
                            key: data.key,
                            timestamp: data.timestamp,
                            sign: data.sign
                        },
                        success(res) {
                            wx.hideLoading()
                            if (JSON.parse(res.data).code == 204) {
                                wx.showModal({
                                    title: '提示',
                                    content: JSON.parse(res.data).error,
                                    showCancel: false
                                })
                                return
                            }
                            wx.showToast({
                                title: '上传图片成功',
                                icon: 'none',
                                duration: 2000
                            })
                            that.setData({
                                goodsActivityImg: JSON.parse(res.data).datas
                            })
                        }
                    })
                } else if (e.currentTarget.dataset.type == 'subImg') {
                    if (that.data.goodsId == null) {
                        let goodsSubImg = that.data.goodsSubImg
                        let tempUrl = 'https://www.meiboshi.vip/api/Upimg/up_vice_img'
                        let tempData = {
                            key: data.key,
                            timestamp: data.timestamp,
                            sign: data.sign
                        }
                        common.uploadImage(tempFilePaths, tempUrl, tempData).then(function(res) {
                            res.forEach((e) => {
                                goodsSubImg.push({
                                    imgUrl: e
                                })
                                that.setData({
                                    goodsSubImg: goodsSubImg
                                })
                            })
                        })
                    } else {
                        let goodsSubImg = that.data.goodsSubImg
                        let tempUrl = 'https://www.meiboshi.vip/api/Goods/add_goods_img'
                        let tempData = {
                            goods_id: that.data.goodsId,
                            type: 4,
                            key: data.key,
                            timestamp: data.timestamp,
                            sign: data.sign
                        }
                        common.uploadImage(tempFilePaths, tempUrl, tempData).then(function(res) {
                            res.forEach((e) => {
                                goodsSubImg.push({
                                    image_id: e.image_id,
                                    imgUrl: e.imgUrl
                                })
                                that.setData({
                                    goodsSubImg: goodsSubImg
                                })
                            })
                        })
                    }
                } else if (e.currentTarget.dataset.type == 'detailImg') {
                    if (that.data.goodsId == null) {
                        let goodsDetailImg = that.data.goodsDetailImg
                        let tempUrl = 'https://www.meiboshi.vip/api/Upimg/up_info_img'
                        let tempData = {
                            key: data.key,
                            timestamp: data.timestamp,
                            sign: data.sign
                        }
                        common.uploadImage(tempFilePaths, tempUrl, tempData).then(function(res) {
                            res.forEach((e) => {
                                goodsDetailImg.push({
                                    imgUrl: e
                                })
                                that.setData({
                                    goodsDetailImg: goodsDetailImg
                                })
                            })
                        })
                    } else {
                        let goodsDetailImg = that.data.goodsDetailImg
                        let tempUrl = 'https://www.meiboshi.vip/api/Goods/add_goods_img'
                        let tempData = {
                            goods_id: that.data.goodsId,
                            type: 5,
                            key: data.key,
                            timestamp: data.timestamp,
                            sign: data.sign
                        }
                        common.uploadImage(tempFilePaths, tempUrl, tempData).then(function(res) {
                            res.forEach((e) => {
                                goodsDetailImg.push({
                                    image_id: e.image_id,
                                    imgUrl: e.imgUrl
                                })
                                that.setData({
                                    goodsDetailImg: goodsDetailImg
                                })
                            })
                        })
                    }
                }
            }
        })
    },

    objKeySort: function(obj) {
        let newkey = Object.keys(obj).sort()
        let newObj = {}
        for (let i = 0; i < newkey.length; i++) {
            newObj[newkey[i]] = obj[newkey[i]]
        }
        return newObj
    }
})